import { Form, Radio, Select, Input, Switch, InputNumber, Tooltip, Card, Row, Col, Badge, Divider, Button } from 'antd';
import { QuestionCircleOutlined, CodeOutlined, BugOutlined, RocketOutlined, ApiOutlined, ArrowRightOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';

interface ContainerSettingsProps {
  onChange?: (values: any) => void;
  onNext?: () => void;
  value?: {
    baseOS?: string;
    systemTools?: string[];
    enableCache?: boolean;
    cacheDir?: string;
    optimizationLevel?: string;
    devToolchain?: string;
    devTools?: string[];
    testFrameworks?: string[];
    testParallel?: number;
    prodOptimizations?: string[];
    targetArch?: string;
    rustVersion?: string;
    toolchainType?: string;
    rustComponents?: string[];
  };
}

const STORAGE_KEY = 'container_settings';

export default function ContainerSettings({ onChange, onNext, value }: ContainerSettingsProps) {
  const [form] = Form.useForm();

  // 初始化表单数据
  useEffect(() => {
    const savedSettings = localStorage.getItem(STORAGE_KEY);
    
    if (savedSettings) {
      try {
        const parsedSettings = JSON.parse(savedSettings);
        form.setFieldsValue(parsedSettings);
      } catch (e) {
        console.error('Failed to parse saved settings:', e);
      }
    }
  }, []);

  // 保存表单数据
  const saveFormData = (values: any) => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(values));
      localStorage.setItem('container_settings_time', new Date().getTime().toString());
      onChange?.(values);
    } catch (e) {
      console.error('Failed to save settings:', e);
    }
  };

  // 检查并清理过期数据
  useEffect(() => {
    const EXPIRY_TIME = 24 * 60 * 60 * 1000; // 24小时
    const now = new Date().getTime();
    const savedTime = localStorage.getItem('container_settings_time');
    
    if (savedTime && (now - parseInt(savedTime)) > EXPIRY_TIME) {
      localStorage.removeItem('container_settings');
      localStorage.removeItem('container_settings_time');
    }
  }, []);

  const handleNext = () => {
    onNext?.();
  };

  return (
    <div className="container-settings">
      <Form 
        form={form}
        layout="vertical"
        onValuesChange={(_, allValues) => saveFormData(allValues)}
      >
        <Divider>基础系统镜像</Divider>
        {/* 基础操作系统层 */}
        <Card
          title={
            <div className="flex items-center">
              <ApiOutlined className="mr-2 text-purple-500" />
              <span>操作系统配置</span>
              <Badge count="BASE" className="ml-2" style={{ backgroundColor: '#8b5cf6' }} />
            </div>
          }
          className="mb-8 os-card"
          extra={<Tooltip title="所有容器共享的基础操作系统配置"><QuestionCircleOutlined /></Tooltip>}
        >
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item
                label="操作系统类型"
                name={['base', 'osType']}
                initialValue="ubuntu"
              >
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value="ubuntu">Ubuntu</Radio.Button>
                  <Radio.Button value="debian">Debian</Radio.Button>
                  <Radio.Button value="alpine">Alpine</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="系统版本"
                name={['base', 'osVersion']}
                initialValue="22.04"
              >
                <Select
                  placeholder="选择系统版本"
                  listHeight={256}
                  options={[
                    { label: 'Ubuntu 22.04 LTS', value: '22.04' },
                    { label: 'Ubuntu 20.04 LTS', value: '20.04' },
                    { label: 'Debian 12', value: 'debian12' },
                    { label: 'Debian 11', value: 'debian11' },
                    { label: 'Alpine 3.19', value: 'alpine3.19' },
                    { label: 'Alpine 3.18', value: 'alpine3.18' },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="系统工具"
                name={['base', 'systemTools']}
                initialValue={['Zsh', 'git', 'curl', 'wget', 'DID']}
                extra={
                  <div className="text-gray-500 text-sm mt-1">
                    <span className="font-medium">DID</span> = Docker in Docker（容器内运行 Docker）
                  </div>
                }
              >
                <Select
                  mode="multiple"
                  placeholder="选择基础系统工具"
                  maxTagCount={5}
                  maxTagTextLength={10}
                  listHeight={256}
                  options={[
                    { label: 'Zsh', value: 'zsh' },
                    { label: 'DID', value: 'DID' },
                    { label: 'Oh-my-zsh', value: 'oh-my-zsh' },
                    { label: 'Git', value: 'git' },
                    { label: 'Curl', value: 'curl' },
                    { label: 'Wget', value: 'wget' },
                    { label: 'Build Essential', value: 'build-essential' },
                    { label: 'Python3', value: 'python3' },
                    { label: 'Node.js', value: 'nodejs' },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>
        </Card>
        
        <Divider>Rust 镜像配置</Divider>

        {/* Rust 配置层 */}
        <Card
          title={
            <div className="flex items-center">
              <div className="w-5 h-5 mr-2 flex items-center justify-center">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-5 h-5">
                  <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
                </svg>
              </div>
              <span>Rust 配置</span>
              <Badge count="RUST" className="ml-2" style={{ backgroundColor: '#FF4B00' }} />
            </div>
          }
          className="mb-8 rust-card"
          extra={
            <Tooltip title="所有容器共享的 Rust 编译器和工具链配置">
              <QuestionCircleOutlined />
            </Tooltip>
          }
        >
          <div className="space-y-6">
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  label="基础组件"
                  name={['base', 'rustComponents']}
                  initialValue={['rust-analyzer']}
                  tooltip="选择需要安装的 Rust 基础组件"
                >
                  <Select
                    mode="multiple"
                    placeholder="选择基础组件"
                    maxTagCount={3}
                    maxTagTextLength={12}
                    listHeight={280}
                    options={[
                      { 
                        label: 'rust-analyzer',
                        value: 'rust-analyzer',
                        children: (
                          <div className="py-2">
                            <div className="font-medium">rust-analyzer</div>
                            <div className="text-xs text-gray-500">提供代码分析、自动补全、跳转定义等 IDE 功能</div>
                          </div>
                        )
                      },
                      { 
                        label: 'rust-clippy',
                        value: 'rust-clippy',
                        children: (
                          <div className="py-2">
                            <div className="font-medium">rust-clippy</div>
                            <div className="text-xs text-gray-500">Rust 官方代码检查工具，提供代码质量建议</div>
                          </div>
                        )
                      },
                      { 
                        label: 'rust-fmt',
                        value: 'rust-fmt',
                        children: (
                          <div className="py-2">
                            <div className="font-medium">rust-fmt</div>
                            <div className="text-xs text-gray-500">Rust 官方代码格式化工具，统一代码风格</div>
                          </div>
                        )
                      }
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Divider orientation="left">其他编译工具集</Divider>
            
            <Form.Item
              label="C/C++ 工具链"
              name={['base', 'cppTools']}
              initialValue={['gcc', 'g++']}
              tooltip="用于编译依赖 C/C++ 的 Rust 项目"
            >
              <Select
                mode="multiple"
                placeholder="选择 C/C++ 工具"
                maxTagCount={3}
                maxTagTextLength={12}
                options={[
                  { 
                    label: 'GCC/G++',
                    value: 'gcc',
                    children: (
                      <div className="py-2">
                        <div className="font-medium">GCC/G++ 编译器</div>
                        <div className="text-xs text-gray-500">GNU C/C++ 编译器，用于编译 C/C++ 依赖</div>
                      </div>
                    )
                  },
                  { 
                    label: 'CMake',
                    value: 'cmake',
                    children: (
                      <div className="py-2">
                        <div className="font-medium">CMake 构建工具</div>
                        <div className="text-xs text-gray-500">跨平台构建工具，用于构建 C/C++ 项目</div>
                      </div>
                    )
                  },
                  { 
                    label: 'LLVM',
                    value: 'llvm',
                    children: (
                      <div className="py-2">
                        <div className="font-medium">LLVM 工具链</div>
                        <div className="text-xs text-gray-500">包含 Clang 编译器和相关工具</div>
                      </div>
                    )
                  }
                ]}
              />
            </Form.Item>

            <Form.Item
              label="系统开发库"
              name={['base', 'sysLibs']}
              tooltip="常用的系统级开发库"
            >
              <Select
                mode="multiple"
                placeholder="选择系统开发库"
                maxTagCount={3}
                maxTagTextLength={12}
                options={[
                  { 
                    label: 'OpenSSL',
                    value: 'openssl-dev',
                    children: (
                      <div className="py-2">
                        <div className="font-medium">OpenSSL 开发库</div>
                        <div className="text-xs text-gray-500">用于加密和 SSL/TLS 功能</div>
                      </div>
                    )
                  },
                  { 
                    label: 'RocksDB',
                    value: 'rocksdb-dev',
                    children: (
                      <div className="py-2">
                        <div className="font-medium">RocksDB 开发库</div>
                        <div className="text-xs text-gray-500">用于持久化键值存储</div>
                      </div>
                    )
                  },
                  { 
                    label: 'ZLib',
                    value: 'zlib-dev',
                    children: (
                      <div className="py-2">
                        <div className="font-medium">ZLib 开发库</div>
                        <div className="text-xs text-gray-500">数据压缩库</div>
                      </div>
                    )
                  }
                ]}
              />
            </Form.Item>
          </div>
        </Card>

        <Divider>容器环境</Divider>

        {/* 开发容器 */}
        <Row gutter={16} className="mb-8">
          <Col span={8}>
            <Card 
              title={
                <div className="flex items-center">
                  <CodeOutlined className="mr-2 text-blue-500" />
                  <span>开发容器</span>
                  <Badge count="DEV" className="ml-2" style={{ backgroundColor: '#2563eb' }} />
                </div>
              }
              className="h-full dev-card"
              extra={<Tooltip title="用于本地开发的容器环境"><QuestionCircleOutlined /></Tooltip>}
            >
              <div className="space-y-4">
                <Form.Item
                  label="编译优化"
                  name={['dev', 'optimization']}
                  initialValue="0"
                >
                  <Radio.Group>
                    <Radio.Button value="0">O0</Radio.Button>
                    <Radio.Button value="1">O1</Radio.Button>
                    <Radio.Button value="2">O2</Radio.Button>
                  </Radio.Group>
                </Form.Item>

                <Form.Item
                  label="调试信息"
                  name={['dev', 'debugInfo']}
                  initialValue={true}
                  valuePropName="checked"
                >
                  <Switch defaultChecked />
                </Form.Item>

                <Form.Item
                  label="开发工具"
                  name={['dev', 'devTools']}
                  initialValue={['clippy', 'rustfmt', 'rust-analyzer']}
                >
                  <Select
                    mode="multiple"
                    placeholder="选择开发工具"
                    options={[
                      { label: 'Clippy (代码检查)', value: 'clippy' },
                      { label: 'Rustfmt (代码格式化)', value: 'rustfmt' },
                      { label: 'Rust Analyzer', value: 'rust-analyzer' },
                      { label: 'GDB', value: 'gdb' },
                      { label: 'LLDB', value: 'lldb' },
                    ]}
                  />
                </Form.Item>

                <Form.Item
                  label="启用缓存"
                  name={['dev', 'enableCache']}
                  valuePropName="checked"
                  initialValue={true}
                >
                  <Switch defaultChecked />
                </Form.Item>

                <Form.Item
                  label="缓存目录"
                  name={['dev', 'cacheDir']}
                  initialValue="/root/.cargo/cache"
                >
                  <Input placeholder="输入缓存目录路径" />
                </Form.Item>
              </div>
            </Card>
          </Col>

          {/* 测试容器 */}
          <Col span={8}>
            <Card 
              title={
                <div className="flex items-center">
                  <BugOutlined className="mr-2 text-yellow-500" />
                  <span>测试容器</span>
                  <Badge count="TEST" className="ml-2" style={{ backgroundColor: '#f59e0b' }} />
                </div>
              }
              className="h-full test-card"
              extra={<Tooltip title="用于服务器端测试的容器环境"><QuestionCircleOutlined /></Tooltip>}
            >
              <div className="space-y-4">
                <Form.Item
                  label="编译优化"
                  name={['test', 'optimization']}
                  initialValue="1"
                >
                  <Radio.Group>
                    <Radio.Button value="0">O0</Radio.Button>
                    <Radio.Button value="1">O1</Radio.Button>
                    <Radio.Button value="2">O2</Radio.Button>
                  </Radio.Group>
                </Form.Item>

                <Form.Item
                  label="测试工具"
                  name={['test', 'testTools']}
                  initialValue={['cargo-test', 'criterion']}
                >
                  <Select
                    mode="multiple"
                    placeholder="选择测试工具"
                    options={[
                      { label: 'Cargo Test', value: 'cargo-test' },
                      { label: 'Criterion (基准测试)', value: 'criterion' },
                      { label: 'Tarpaulin (代码覆盖)', value: 'tarpaulin' },
                      { label: 'Nextest', value: 'nextest' },
                    ]}
                  />
                </Form.Item>

                <Form.Item
                  label="并行测试数"
                  name={['test', 'testParallel']}
                  initialValue={4}
                >
                  <InputNumber min={1} max={16} />
                </Form.Item>

                <Form.Item
                  label="启用缓存"
                  name={['test', 'enableCache']}
                  valuePropName="checked"
                  initialValue={true}
                >
                  <Switch defaultChecked />
                </Form.Item>
              </div>
            </Card>
          </Col>

          {/* 生产容器 */}
          <Col span={8}>
            <Card 
              title={
                <div className="flex items-center">
                  <RocketOutlined className="mr-2 text-green-500" />
                  <span>生产容器</span>
                  <Badge count="PROD" className="ml-2" style={{ backgroundColor: '#10b981' }} />
                </div>
              }
              className="h-full prod-card"
              extra={<Tooltip title="用于生产环境部署的容器环境"><QuestionCircleOutlined /></Tooltip>}
            >
              <div className="space-y-4">
                <Form.Item
                  label="编译优化"
                  name={['prod', 'optimization']}
                  initialValue="3"
                >
                  <Radio.Group>
                    <Radio.Button value="2">O2</Radio.Button>
                    <Radio.Button value="3">O3</Radio.Button>
                  </Radio.Group>
                </Form.Item>

                <Form.Item
                  label="发布优化"
                  name={['prod', 'prodOptimizations']}
                  initialValue={['lto']}
                >
                  <Select
                    mode="multiple"
                    placeholder="选择发布优化选项"
                    options={[
                      { label: 'LTO (链接时优化)', value: 'lto' },
                      { label: '代码精简', value: 'codegen-units-1' },
                      { label: '符号剥离', value: 'strip' },
                    ]}
                  />
                </Form.Item>

                <Form.Item
                  label="目标架构"
                  name={['prod', 'targetArch']}
                  initialValue="native"
                >
                  <Select
                    placeholder="选择目标架构"
                    options={[
                      { label: '本机优化', value: 'native' },
                      { label: 'x86_64通用', value: 'x86_64' },
                      { label: 'ARM64', value: 'aarch64' },
                    ]}
                  />
                </Form.Item>

                <Form.Item
                  label="启用缓存"
                  name={['prod', 'enableCache']}
                  valuePropName="checked"
                  initialValue={true}
                >
                  <Switch defaultChecked />
                </Form.Item>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 下一步按钮 */}
        <div className="flex justify-end mt-8">
          <Button type="primary" size="large" className="next-step-btn" onClick={handleNext}>
            下一步 
          </Button>
        </div>

        <style jsx global>{`
          .container-settings .ant-card {
            height: 100%;
            transition: all 0.3s ease;
          }
          .container-settings .ant-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }
          
          /* 操作系统卡片样式 */
          .os-card {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(139, 92, 246, 0.5), rgba(139, 92, 246, 0.3)) border-box !important;
          }
          .os-card:hover {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(139, 92, 246, 0.7), rgba(139, 92, 246, 0.5)) border-box !important;
          }

          /* Rust配置卡片样式 */
          .rust-card {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(255, 75, 0, 0.5), rgba(255, 75, 0, 0.3)) border-box !important;
          }
          .rust-card:hover {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(255, 75, 0, 0.7), rgba(255, 75, 0, 0.5)) border-box !important;
          }

          /* 开发容器卡片样式 */
          .dev-card {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(37, 99, 235, 0.5), rgba(37, 99, 235, 0.3)) border-box !important;
          }
          .dev-card:hover {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(37, 99, 235, 0.7), rgba(37, 99, 235, 0.5)) border-box !important;
          }

          /* 测试容器卡片样式 */
          .test-card {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(245, 158, 11, 0.5), rgba(245, 158, 11, 0.3)) border-box !important;
          }
          .test-card:hover {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(245, 158, 11, 0.7), rgba(245, 158, 11, 0.5)) border-box !important;
          }

          /* 生产容器卡片样式 */
          .prod-card {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(16, 185, 129, 0.5), rgba(16, 185, 129, 0.3)) border-box !important;
          }
          .prod-card:hover {
            border: 2px solid transparent !important;
            background: linear-gradient(#fff, #fff) padding-box,
                        linear-gradient(to right, rgba(16, 185, 129, 0.7), rgba(16, 185, 129, 0.5)) border-box !important;
          }

          /* 下一步按钮样式 */
          .next-step-btn {
            background: #2563eb;
            border: none;
            padding: 0 24px;
            height: 44px;
            border-radius: 8px;
            font-size: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
          }

          .next-step-btn:hover {
            background: #1d4ed8;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);
          }

          .container-settings .ant-form-item {
            margin-bottom: 16px;
          }
          .container-settings .ant-divider {
            margin: 24px 0;
            color: #6b7280;
            font-size: 14px;
          }
          .container-settings .ant-select {
            width: 100%;
          }
          .container-settings .ant-select-selection-item {
            padding: 4px 8px !important;
            height: auto !important;
            line-height: 1.5 !important;
          }
          .container-settings .ant-select-multiple .ant-select-selection-item {
            height: auto !important;
            line-height: 1.5 !important;
            margin-top: 2px !important;
            margin-bottom: 2px !important;
          }
          .container-settings .ant-select-dropdown .ant-select-item {
            padding: 8px 12px;
          }
          .container-settings .ant-select-dropdown .ant-select-item-option-content {
            white-space: normal;
            line-height: 1.5;
          }
          .container-settings .ant-input {
            width: 100%;
            padding: 4px 11px;
          }
          .container-settings .ant-radio-button-wrapper {
            padding: 0 16px;
            height: 32px;
            line-height: 30px;
          }
          .container-settings .ant-select-selection-search {
            margin-inline-start: 0;
          }
          .container-settings .ant-select-selection-placeholder {
            padding: 0 8px;
          }
          .container-settings .ant-badge-count {
            height: 20px;
            line-height: 20px;
            padding: 0 8px;
            font-size: 12px;
            font-weight: normal;
          }

          /* 添加过期时间清理 */
          @media (prefers-reduced-motion: no-preference) {
            .container-settings {
              opacity: 1;
              transition: opacity 0.3s ease;
            }
          }
        `}</style>
      </Form>
    </div>
  );
} 